<template>
  <el-dialog
    v-if="visible"
    v-el-drag-dialog
    :title="title"
    :visible.sync="visible"
    width="60vw"
    @close="reset"
  >
    <div class="rechargeRuleSetting-configuration">
      <el-form
        ref="dataForm"
        class="form"
        :rules="rules"
        :model="form"
        label-position="left"
        label-width="150px"
      >
        <div class="deposit_header">费用配置</div>
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="实体卡开卡工本费:" prop="workFeeOne">
              <el-input
                id="workFeeOne"
                v-model="form.workFeeOne"
                oninput="value=value.replace(/[^0-9.]/g,'')"
                maxlength="5"
                @blur="moneyInoutBlur"
              >
                <span slot="append">元</span>
              </el-input>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="虚拟卡开卡工本费:" prop="workFeeTwo">
              <el-input
                id="workFeeTwo"
                v-model="form.workFeeTwo"
                maxlength="5"
                oninput="value=value.replace(/[^0-9.]/g,'')"
                @blur="moneyInoutBlur"
              >
                <span slot="append">元</span>
              </el-input>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="单次储值上限:" prop="singleRecharge">
              <el-input
                id="singleRecharge"
                v-model="form.singleRecharge"
                oninput="value=value.replace(/[^0-9.]/g,'')"
                @blur="moneyInoutBlur"
              >
                <span slot="append">元</span>
              </el-input>
            </el-form-item>
          </el-col>
        </el-row>
        <div class="deposit_header">交易配置</div>
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="卡值消费方式:" prop="cardPayWay">
              <el-select v-model="form.cardPayWay" placeholder="请选择">
                <el-option
                  v-for="item in CARDPAYWAYOPTIONS"
                  :key="item.value"
                  :label="item.label"
                  :value="item.value"
                />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="线上储值:" prop="onlineWay">
              <el-select v-model="form.onlineWay" placeholder="请选择">
                <el-option
                  v-for="item in ONLINEWAYOPTIONS"
                  :key="item.value"
                  :label="item.label"
                  :value="item.value"
                />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="交易校验:" prop="checkWay">
              <el-select v-model="form.checkWay" placeholder="请选择">
                <el-option
                  v-for="item in CHECKWAYOPTIONS"
                  :key="item.value"
                  :label="item.label"
                  :value="item.value"
                />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="线上支付设置:" prop="onLinePayType">
              <el-select v-model="form.onLinePayType" placeholder="请选择">
                <el-option
                  v-for="item in ONLINEPAYTYPEOPTIONS"
                  :key="item.value"
                  :label="item.label"
                  :value="item.value"
                />
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
        <!-- <el-row :gutter="20">
          <el-col :span="8">
            <el-form-item label="线上支付设置:" prop="onLinePayType">
              <el-select v-model="form.onLinePayType" placeholder="请选择">
                <el-option
                  v-for="item in ONLINEPAYTYPEOPTIONS"
                  :key="item.value"
                  :label="item.label"
                  :value="item.value"
                />
              </el-select>
            </el-form-item>
          </el-col>
        </el-row> -->
        <div class="deposit_header">消费不适用范围</div>
        <el-row>
          <el-col :span="12">
            <div class="rechargeRuleSetting-configuration_orgSNNo">
              <el-tree-select
                ref="treeSelect"
                v-model="form.noUserOrg"
                :clearable="false"
                class="tree-select"
                :popover-width="360"
                :collapse-tags="false"
                :select-params="{
                  clearable: true,
                  placeholder: '请选择消费不适用范围',
                  loading: $loadingPlugin.getTreeData,
                  multiple: true,
                }"
                :tree-params="{
                  'expand-on-click-node': false,
                  'highlight-current': true,
                  'check-strictly': true,
                  props: {
                    value: 'orgId',
                    label: 'orgName',
                    disabled: 'disabled',
                  },
                  data: treeData,
                }"
                @check="handleCheckChange"
                @node-click="selectTreeChange"
              />
              <el-button
                size="mini"
                type="primary"
                @click="add"
              >添加</el-button>
            </div>

            <el-form-item
              prop="noUserOrg"
              class="rechargeRuleSetting-configuration_noUserOrg"
            >
              <el-input v-model="form.noUserOrgText" type="textarea" :rows="6" disabled />
            </el-form-item>
          </el-col>
        </el-row>
        <div class="config-item">
          <div class="deposit_header">余额预警提醒配置</div>
          <el-popover
            class="config-tip"
            placement="right"
            width="600"
            trigger="hover"
          >
            <div>
              <p>功能说明：</p>
              <p>使用余额预警提醒功能可以给指定手机号码发送预警通知短信以便提醒用户充值。当功能开启时，管理者可以配置预警提醒余额值和短信通知时间，系统根据配置进行短信通知提醒。</p>
            </div>
            <i slot="reference" class="el-icon-question radio-icon" />
          </el-popover>
        </div>

        <el-row>
          <el-col :span="24">
            <el-form-item label="余额预警提醒：" prop="balanceWarning">
              <el-radio-group v-model="form.balanceWarning" @change="balanceWarningChange">
                <el-radio :label="-1">关闭</el-radio>
                <el-radio :label="1">开启</el-radio>
              </el-radio-group>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row v-if="form.balanceWarning===1" :gutter="20">
          <el-col :span="12">
            <el-form-item label="预警提醒额度:" prop="balanceWarningLimit">
              <el-input
                v-model="form.balanceWarningLimit"
                oninput="value=value.replace(/[^0-9.]/g,'')"
                maxlength="5"
                @blur="moneyInoutBlur"
              >
                <span slot="append">元</span>
              </el-input>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="短信通知手机号:" prop="warningPhone">
              <el-input v-model.trim="form.warningPhone" maxlength="11" />
            </el-form-item>
          </el-col>
          <el-col :span="20">
            <el-form-item label="短信通知时间:" prop="warningTime" class="inputLabel">
              <span>每日</span>
              <el-time-picker
                v-model="form.warningTime"
                format="HH:mm:ss"
                value-format="HH:mm:ss"
                placeholder="请选择"
              />
              <span>时</span><span>，自动发送</span>
            </el-form-item>
          </el-col>
        </el-row>

      </el-form>
      <!-- <div class="rechargeRuleSetting-btn">
        <el-button v-permission="9" type="primary" @click="save">保存设置</el-button>
      </div> -->
    </div>
    <div slot="footer" class="dialog-footer">
      <el-button @click="visible = false">关闭</el-button>
      <el-button type="primary" :loading="$loadingPlugin.save" @click="save">保存设置</el-button>
    </div>
  </el-dialog>
</template>

  <script>
  import getTreeData from '@/utils/jsonTree'
  import { mapGetters } from 'vuex'
  import { csmcardconfigQuery, csmcardconUpdate } from '@/api'
  import {
    CARDPAYWAYOPTIONS,
    ONLINEWAYOPTIONS,
    CHECKWAYOPTIONS,
    ONLINEPAYTYPEOPTIONS
  } from '../js/config'
  export default {
    data() {
      const validteNumber = (rule, value, callback) => {
        if (value && Number(value) > 5000000) {
          return callback(new Error('单次储值上限最大为5000000元'))
        } else {
          callback()
        }
      }
      return {
        CARDPAYWAYOPTIONS,
        ONLINEWAYOPTIONS,
        CHECKWAYOPTIONS,
        ONLINEPAYTYPEOPTIONS,
        visible: false,
        title: '充值业务配置',
        form: {
          workFeeOne: '', // 实体卡工本费
          workFeeTwo: '', // 虚拟卡工本费
          singleRecharge: '', // 单次储值上限
          cardPayWay: '', // 卡值消费方式(1:表示先现金2:表示先赠送)
          onlineWay: '', // 线上储值方式(1:开通;2:不开通)
          checkWay: '', // 交易校验(1:无校验；2:仅密码校验;3:仅验证码校验；4:密码和验证码均可校验)
          noUserOrg: [], // 消费不适用范围
          onLinePayType: '', // 线上支付设置PAY_ALL(1, "所有关联微信均可支付"),     PAY_PHONE(2, "仅允许绑定手机号关联的微信支付");
          noUserOrgText: '',
          balanceWarning: -1,
          warningTime: '',
          balanceWarningLimit: '',
          warningPhone: ''
        },
        rules: {
          noUserOrg: [
            { required: false, message: '请选择消费不适用范围', trigger: 'change' }
          ],
          workFeeOne: [
            { required: true, message: '请输入实体卡工本费', trigger: 'change' }
          ],
          workFeeTwo: [
            { required: true, message: '请输入虚拟卡工本费', trigger: 'change' }
          ],
          singleRecharge: [
            { required: true, message: '请输入单次储值上限', trigger: 'change' },
            { validator: validteNumber, trigger: 'blur' }
          ],
          cardPayWay: [
            { required: true, message: '请选择卡值消费方式', trigger: 'change' }
          ],
          onlineWay: [{ required: true, message: '请选择线上储值方式', trigger: 'change' }],
          checkWay: [{ required: true, message: '请选择交易校验', trigger: 'change' }],
          onLinePayType: [
            { required: true, message: '请选择线上支付设置', trigger: 'change' }
          ],
          balanceWarning: [
            { required: true, message: '请选择余额预警提醒', trigger: 'change' }
          ],
          balanceWarningLimit: [
            { required: true, message: '请输入预警提醒额度', trigger: 'change' }
          ],
          warningPhone: [
            { required: true, message: '请输入短信通知手机号', trigger: 'change' }
          ],
          warningTime: [
            { required: true, message: '请选择短信通知时间', trigger: 'change' }
          ]
        }
      }
    },
    computed: {
      ...mapGetters(['orgList'])
    },
    async created() {
      await this.getTreeData()
    },
    // mounted() {
    //   this.getCsmcardconfigData()
    // },
    methods: {
      // 获取适用机构数据
      async getTreeData() {
        const data = this.orgList.map((item) => ({
          label: item.orgName,
          ...item
        }))
        this.treeData = getTreeData(data)
      },
      handleCheckChange(value) {
      },
      selectTreeChange(value) {},
      // 金额输入框失去焦点保留2位小数
      moneyInoutBlur(e) {
        const key = e.target.id
        this.form[key] = ((this.form[key] * 100) / 100).toFixed(2)
      },
      // 添加不适用范围
      add() {
        this.form.noUserOrgText = this.$refs['treeSelect'].labels.toString()
      },
      // 获取充值规则设置
      async getCsmcardconfigData() {
        const { status, data } = await csmcardconfigQuery()
        console.log(data)
        if (status === 200) {
          // 设置默认值
          for (const key in this.form) {
            const moneyKey = ['workFeeOne', 'workFeeTwo', 'singleRecharge']
            if (moneyKey.includes(key)) {
              if (key === 'singleRecharge' && (data[key] / 100) > 5000000) {
                this.form[key] = '5000000.00'
              } else {
                this.form[key] = (data[key] / 100).toFixed(2)
              }
            } else if (key === 'noUserOrg') {
              this.form[key] = data[key].split(',')
            } else {
              this.form[key] = data[key]
            }
          }
          console.log(this.form.singleRecharge)
          // 设置
          this.$nextTick(() => {
            this.form.noUserOrgText = this.$refs['treeSelect'] ? this.$refs['treeSelect'].labels.toString() : ''
          })
        }
      },
      balanceWarningChange() {
        if (this.form.balanceWarning === -1) {
          this.form.warningTime = ''
          this.form.balanceWarningLimit = ''
          this.form.warningPhone = ''
        }
      },
      // 提交配置
      save() {
        this.$refs.dataForm.validate(async(valid) => {
          if (!valid) return
          await this.submit()
          this.visible = false
        })
      },
      async submit() {
        // let params = JSON.parse(JSON.stringify(this.form))
        // params.noUserOrg = params.noUserOrg.toString()
        const params = {
          workFeeOne: Number(this.form.workFeeOne) * 100, // 实体卡工本费
          workFeeTwo: Number(this.form.workFeeTwo) * 100, // 虚拟卡工本费
          singleRecharge: Number(this.form.singleRecharge) * 100, // 单次储值上限
          cardPayWay: this.form.cardPayWay, // 卡值消费方式(1:表示先现金2:表示先赠送)
          onlineWay: this.form.onlineWay, // 线上储值方式(1:开通;2:不开通)
          checkWay: this.form.checkWay, // 交易校验(1:无校验；2:仅密码校验;3:仅验证码校验；4:密码和验证码均可校验)
          noUserOrg: this.form.noUserOrg.toString(), // 消费不适用范围
          onLinePayType: this.form.onLinePayType, // 线上支付设置PAY_ALL(1, "所有关联微信均可支付"),     PAY_PHONE(2, "仅允许绑定手机号关联的微信支付");
          balanceWarning: this.form.balanceWarning,
          warningTime: this.form.warningTime,
          balanceWarningLimit: this.form.balanceWarningLimit,
          warningPhone: this.form.warningPhone
        }
        const { status } = await csmcardconUpdate(params)
        if (status === 200) {
          this.$notify({
            title: '提示',
            message: '信息保存成功',
            type: 'success',
            duration: 2000
          })
        }
      },
      reset() {
        this.form = {
          workFeeOne: '', // 实体卡工本费
          workFeeTwo: '', // 虚拟卡工本费
          singleRecharge: '', // 单次储值上限
          cardPayWay: '', // 卡值消费方式(1:表示先现金2:表示先赠送)
          onlineWay: '', // 线上储值方式(1:开通;2:不开通)
          checkWay: '', // 交易校验(1:无校验；2:仅密码校验;3:仅验证码校验；4:密码和验证码均可校验)
          noUserOrg: [], // 消费不适用范围
          onLinePayType: '', // 线上支付设置PAY_ALL(1, "所有关联微信均可支付"),     PAY_PHONE(2, "仅允许绑定手机号关联的微信支付");
          noUserOrgText: '',
          balanceWarning: -1,
          warningTime: '',
          balanceWarningLimit: '',
          warningPhone: ''
        }
      },
      open() {
        return new Promise(resolve => {
          this.resolve = resolve
          this.reset()
          this.getCsmcardconfigData()
          this.visible = true
        })
      }
    }
  }
  </script>

  <style lang="scss" scoped>
  .rechargeRuleSetting-configuration {
    // min-height: 100%;
    /deep/.el-select {
      width: 100%;
      height: 32px;
    }
    /deep/.el-select__tags {
      flex-wrap: nowrap;
      overflow: auto;
      &::-webkit-scrollbar {
        display: none;
      }
    }

    .deposit_header {
      margin: 15px;
      font-size: 14px;
      font-weight: bold;
    }
    /deep/.el-row {
      padding-left: 50px;
    }
    .rechargeRuleSetting-configuration_noUserOrg {
      /deep/.el-form-item__content {
        margin-left: 0 !important;
      }
    }
    .rechargeRuleSetting-configuration_orgSNNo {
      display: flex;
      margin-bottom: 10px;

      .tree-select {
        margin-right: 10px;
      }
    }
    .rechargeRuleSetting-btn {
      padding-top: 50px;
      text-align: center;
    }
  }
  .config-item {
    display: flex;
    align-items: center;
  }
  .radio-icon {
    cursor: pointer;
  }
  .inputLabel {
    min-width: 250px;
    /deep/ .el-date-editor {
      width: 120px;
    }
  }
  </style>
